package net.xuele.learn.IO.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * Created by GaoQingming on 2019/4/12 0012.
 * <p>
 * 接受客户端连接的回调
 */
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimerServerHandler> {


    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimerServerHandler attachment) {
        // 运行到此处表示已经接收到客户端的连接了，但是此处仍在接受连接，是因为有成千上万个客户端与服务端连接！！！
        System.out.println("connected!!!");
        attachment.channel.accept(attachment, this);
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        // 读取客户端发送过来的消息！！！异步的！！！
        result.read(allocate, allocate, new ReadCompletionHandler(result));
    }

    @Override
    public void failed(Throwable exc, AsyncTimerServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}
